package com.aplink.generic.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;

import com.aplink.generic.cache.MasterConfigManager;
import com.aplink.generic.sharepreference.GenericSharePreference;

public class DatabaseBackup {
	public void writeToSD(final Context context) throws IOException {
		final File sd = Environment.getExternalStorageDirectory();
		if (sd.canWrite()) {
			final String DATABASE_NAME = MasterConfigManager
			        .getInstance()
			        .get(GenericSharePreference.getInstance()
			                .getMasterConfigFileID()).getDatabaseName();
			final String backupDBPath = String.format("bak_%s", DATABASE_NAME);
			final File currentDB = context.getDatabasePath(DATABASE_NAME);
			final File backupDB = new File(sd, backupDBPath);
			backupDB.createNewFile();
			if (currentDB.exists()) {
				final FileInputStream fileInputStream = new FileInputStream(
				        currentDB);
				final FileOutputStream fileOutputStream = new FileOutputStream(
				        backupDB);
				final byte[] buffer = new byte[1024];
				while (fileInputStream.read(buffer) != -1) {
					fileOutputStream.write(buffer);
				}
				fileInputStream.close();
				fileOutputStream.close();
			}
		}
	}
}
